package rsj.service.account;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.TableNode;
import common.statusenum.StatusEnum;
import common.util.validator.ParameterConversionCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import rsj.api.account.entity.AccountProduct;
import rsj.api.account.entity.CheckDeleteResult;
import rsj.api.account.entity.DeleteAccountParam;
import rsj.service.contract.IContractService;
import rsj.sql.account.AccountProductDao;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 权限
 *
 * @author yuanqinglong
 * @since 2021/7/15 8:54
 */
@Service
public class AccountProductServiceImpl implements IAccountProductService {

    @Autowired
    private AccountProductDao accountProductDao;

    @Autowired
    private IContractService contractServiceImpl;



    /**
     * 更新账户产品
     *
     * @param accountProducts 账户的产品
     * @param orgId           机构id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAccountProduct(List<AccountProduct> accountProducts, String orgId) {
        this.deleteAccountProduct(Collections.singletonList(orgId));
        if (CollectionUtils.isEmpty(accountProducts)) {
            return;
        }
        accountProducts.forEach(ParameterConversionCheck::parameterConversionCheckFastFail);
        LocalDateTime now = LocalDateTime.now();
        for (AccountProduct accountProduct : accountProducts) {
            accountProduct.setUpdateTm(now);
            accountProduct.setOrgId(orgId);
            accountProductDao.addAccountProduct(accountProduct);
        }
    }




    /**
     * 删除账户产品
     *
     * @param orgIds 机构id
     */
    @Override
    public void deleteAccountProduct(List<String> orgIds) {
        accountProductDao.deleteAccountProduct(orgIds);
    }

    /**
     * 获得权限
     *
     * @param orgId 机构id
     * @return {@link List<AccountProduct>}
     */
    @Override
    public List<AccountProduct> getAccountProducts(String orgId) {
        TableNode accountProducts = accountProductDao.getAccountProducts(orgId);
        return JSON.parseArray(accountProducts.toJson(), AccountProduct.class);
    }

    /**
     * 检查删除
     *
     * @param deleteAccountParam 删除账户参数
     * @return {@link CheckDeleteResult}
     */
    @Override
    public CheckDeleteResult checkDelete(DeleteAccountParam deleteAccountParam) {
        List<String> contractedProduct = contractServiceImpl.checkContractedProduct(deleteAccountParam.getOrgId(), deleteAccountParam.getProdUid());
        if (!CollectionUtils.isEmpty(contractedProduct)) {
            return new CheckDeleteResult(StatusEnum.NO.getCode(), String.join(",", contractedProduct));
        }
        return new CheckDeleteResult(StatusEnum.YES.getCode(), "");
    }


}
